package com.easytopit.demo.spring.mvc.controller;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.DataBinder;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.easytopit.demo.spring.mvc.domain.CusValidUser;

@Controller
@RequestMapping("/valid/cus")
public class ValidCusController {

	// 定义一个验证器: 专用于CusValidUser对象
	class UserValidator implements Validator {

		public boolean supports(Class<?> clazz) {
			// 判断: CusValidUser 类才启动该验证器
			return CusValidUser.class.equals(clazz);
		}

		public void validate(Object obj, Errors errors) {
			CusValidUser user = (CusValidUser) obj;
			ValidationUtils.rejectIfEmpty(errors, "id", null, "ID不能为null");
			
			ValidationUtils.rejectIfEmpty(errors, "name", null, "用户名不能为null");
			String name = user.getName();
			if(name.length() > 20 || name.length() < 3){
				errors.rejectValue("name", null, new Object[]{3, 20}, "用户名长度需要在{0}~{1}之间x");	
			}
			
			ValidationUtils.rejectIfEmpty(errors, "age", null, "年龄不能为null");
			Integer age = user.getAge();
			if(age == null || age > 46 || age < 16){
				errors.rejectValue("name", null, new Object[]{16, 46}, "年龄必须在{0}~{1}之间x");	
			}
			
			ValidationUtils.rejectIfEmpty(errors, "addr", null, "地址不能为null");
		}

	}

	// 注册验证器: 告知Spring 后续使用自定义的验证器进行验证
	@InitBinder
	public void initBinder(DataBinder binder) {
		binder.setValidator(new UserValidator());
	}

	@GetMapping("/index")
	public String index(@ModelAttribute("user") CusValidUser testObject) {
		return "valid/cus_valid";
	}

	@PostMapping("/post")
	public String post(@Valid @ModelAttribute("user") CusValidUser testObject, BindingResult result) {
		if (!result.hasErrors()) {
			System.out.println("验证成功");
			return "valid/ok";
		}
		return "valid/cus_valid";
	}

}
